<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :span="24">
        <el-col :span="12">
          <el-form-item label="申请编号" prop="applyCode">
            <el-input v-model="formData.applyCode" placeholder="请输入申请编号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人" prop="applyUserId">
            <UserSelect
              v-model="formData.applyUserId"
              placeholder="请选择申请人"
              clearable
              filterable
              @change="onChangeUser"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="formData.phone" placeholder="自动带出" clearable disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用期限" prop="useEndTime">
            <el-date-picker
              v-model="formData.useEndTime"
              value-format="x"
              type="datetime"
              placeholder="使用期限"
              :default-time="new Date('1 23:59:59')"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="使用理由" prop="applyReson">
            <el-input v-model="formData.applyReson" type="textarea" placeholder="请输入使用理由" clearable maxlength="200" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件" prop="file">
            <UploadFile 
              v-model="formData.file" 
              :limit="1"
              :fileType="fileExtsApplyList"
              :fileSize="200"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">数字资源</el-divider>
      <el-form-item prop="sourceApplyDetails" label-width="0">
        <div class="flex items-center justify-end" style="width: 100%;">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <el-table :data="formData.sourceApplyDetails" :stripe="true" :show-overflow-tooltip="true">
          <!-- <el-table-column label="主键" align="center" prop="id" /> -->
          <el-table-column label="#" align="center" type="index" width="50" fixed="left" />
<!--          <el-table-column label="封面" align="center" prop="mainImage">
            <template #default="scope">
              <el-image
                style="width: 44px; height: 44px;"
                :src="scope.row.mainImage"
                :preview-src-list="[scope.row.mainImage]"
                fit="cover"
              />
            </template>
          </el-table-column>-->
          <el-table-column label="资源名称" align="center" prop="sourceName" />
          <el-table-column label="资源类型" align="center" prop="sourceType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SOURCE_TYPE" :value="scope.row.sourceType" />
            </template>
          </el-table-column>
          <el-table-column label="来源信息" align="center" prop="sourceDesc">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SOURCE_DESC" :value="scope.row.sourceDesc" />
            </template>
          </el-table-column>
          <el-table-column label="资源来源" align="center" prop="sourceFrom">
            <template #default="scope">
              <!-- <dict-tag :type="DICT_TYPE.SOURCE_FROM" :value="scope.row.sourceFrom" /> -->
              {{ scope.row.sourceFrom }}
            </template>
          </el-table-column>
          <el-table-column label="文件类型" align="center" prop="fileType" />
          <el-table-column label="主题分类" align="center" prop="catalogClassify">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.JOURNAL_TYPE" :value="scope.row.catalogClassify" />
            </template>
          </el-table-column>
          <el-table-column label="资源标签" align="center" prop="catalogTags">
            <template #default="scope">
              <DictCataTag :value="scope.row.catalogTags" />
            </template>
          </el-table-column>
          <el-table-column label="存放位置" align="center" prop="catalogStore" />
          <el-table-column label="资源描述" align="center" prop="catalogDesc">
            <template #default="scope">
              <span v-html="scope.row.catalogDesc"></span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column
            label="更新时间"
            align="center"
            prop="updateTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="120px" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openDetail(scope.row)"
                v-hasPermi="['dr:source:query']"
              >
                详情
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm('save')" type="primary" :disabled="formLoading">暂 存</el-button>
      <el-button @click="submitForm('submit')" type="primary" :disabled="formLoading">提 交</el-button>
    </template>

    <!-- 资源详情 -->
    <SourceCataDetail v-model:visible="detailVisible" :data="currentRow" />
    <!-- 资源搜索 -->
    <SourceCataSelectDialog
      v-model:visible="detailSourceSelectVisible"
      v-model="formData.sourceApplyDetails"
      type="apply"
    />
  </Dialog>
</template>
<script setup lang="ts">
import { useUserStore } from '@/store/modules/user'
import { getStrDictOptions, fileExtsApplyList, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { SourceApplyApi, SourceApplyVO } from '@/api/dr/sourceapply'
import { getSimpleUserList } from '@/api/system/user'
import { SourceVO } from '@/api/dr/source'
const userStore = useUserStore()
/** 资源申请 表单 */
defineOptions({ name: 'SourceApplyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const applyUserList = ref<any>([]) // 申请人列表
const formData = ref<any>({
  id: undefined,
  applyCode: undefined,
  applyUserId: userStore.getUser?.id,
  phone: undefined,
  useEndTime: undefined,
  applyReson: undefined,
  file: undefined,
  sourceApplyDetails: [],
})
const formRules = reactive({
  applyUserId: [
    {
      required: true,
      message: '请输入申请人',
      trigger: ['blur', 'change'],
    },
  ],
  useEndTime: [
    {
      required: true,
      message: '请选择使用期限',
      trigger: ['blur', 'change'],
    },
  ],
})
const formRef = ref() // 表单 Ref
const detailVisible = ref<boolean>(false)
const currentRow = ref<SourceVO>()
const detailSourceSelectVisible = ref<boolean>(false)
// 新增资源
const handleAdd = () => {
  detailSourceSelectVisible.value = true
}
const handleDelete = (id: number) => {
  formData.value.sourceApplyDetails = formData.value.sourceApplyDetails.filter((item: SourceVO) => item.id !== id)
}
// 详情弹窗
const openDetail = (row: any) => {
  currentRow.value = { ...row }
  detailVisible.value = true
}
const onChangeUser = (value: any, e:any) => {
  // console.log('onChangeUser', value, e)
  formData.value.phone = e.mobile
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SourceApplyApi.getSourceApply(id)
      if(type === 'create' && id) {
        delete formData.value.id
      }
      formData.value.sourceApplyDetails = formData.value.sourceList?.slice() || []
      delete formData.value.sourceList
    } finally {
      formLoading.value = false
    }
  }

  getSimpleUserList().then(list => {
    // console.log('getSimpleUserList', list)
    applyUserList.value = list
  })
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type?:string) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SourceApplyVO
    data.operateFlag = type
    data.sourceApplyDetails = data.sourceApplyDetails?.map((v:any) => ({
      ...v,
      sourceId: v.sourceId,
    }))
    if (formType.value === 'create') {
      await SourceApplyApi.createSourceApplyBpm(data)
      message.success(t('common.createSuccess'))
    } else {
      await SourceApplyApi.updateSourceApply(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    applyCode: undefined,
    applyUserId: userStore.getUser?.id,
    phone: undefined,
    useEndTime: undefined,
    applyReson: undefined,
    file: undefined,
    sourceApplyDetails: [],
  }
  formRef.value?.resetFields()
}
</script>
